import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
import 'package:just_audio/just_audio.dart';

class AudioHelper {
  static final AudioHelper _instance = AudioHelper._internal();
  factory AudioHelper() => _instance;
  AudioHelper._internal();

  final AudioPlayer _audioPlayer = AudioPlayer();

  /// 从Base64播放音频
  Future<void> playAudioFromBase64(String base64Audio, String format) async {
    try {
      // 解码Base64音频数据
      final Uint8List audioBytes = base64Decode(base64Audio);

      //先停止下正在播放的音频
      if(_audioPlayer.playing){
        await stopAudio();
      }

      // 创建临时文件
      final tempDir = await getTemporaryDirectory();
      final tempPath = '${tempDir.path}/temp_audio.$format';
      final tempFile = File(tempPath);

      // 写入音频数据
      await tempFile.writeAsBytes(audioBytes);

      // 播放音频
      await _audioPlayer.setFilePath(tempPath);
      await _audioPlayer.play();
    } catch (e) {
      throw Exception('播放音频失败: $e');
    }
  }

  /// 停止播放
  Future<void> stopAudio() async {
    await _audioPlayer.stop();
  }

  /// 释放资源
  Future<void> dispose() async {
    await _audioPlayer.dispose();
  }
}